'''
字符串与字节码相互转换
# 将字符串转变为字节码
some_bytes = r'你好，世界。上海人民'.encode('gbk')
print(some_bytes,type(some_bytes))

# 将字节码转变为字符串
some_string = some_bytes.decode('gbk')
# some_string = some_bytes.decode('utf-8')
print(some_string,type(some_string))

'''


import sys,chardet

from chardet.universaldetector import UniversalDetector
import chardet




def GetEncoding(file):
    """
    获取文本文件的编码类型
    :param file:
    :return: 返回值是字典 {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
    """
    txt = open(file, "rb")
    detector = UniversalDetector()
    for line in txt.readlines():
        detector.feed(line)
        if detector.done:
            break
            # pass
    detector.close()
    txt.close()
    return detector.result



print(sys.getdefaultencoding())

# 将字符串转变为字节码
some_bytes = r'你好，世界。上海人民'.encode('gbk')
print(some_bytes,type(some_bytes))

# 将字节码转变为字符串
some_string = some_bytes.decode('gbk')
# some_string = some_bytes.decode('utf-8')
print(some_string,type(some_string))


char_encoding= chardet.detect(some_bytes)
print(f'该字符串为：{some_bytes}')
print(f'该字符串编码信息为：{char_encoding}' ) 
print(f'该字符串编码为： {char_encoding["encoding"]}')

detector = UniversalDetector()
detector.feed(some_bytes)
if detector.done:
    print(some_bytes,type(some_bytes))

detector.close()
print(detector.result)